package ee.siimoliver.chat.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

import ee.siimoliver.chat.errors.SyntaxError;

public class JsonParser implements Const{
	
	public static void createAndPopulateJsonFile(String fileName) {
		try {
			File file = new File(fileName);
			if (!file.exists()) {
				PrintWriter pw = new PrintWriter(file);
				pw.println("[");
				pw.println(Const.DEFAULT_USER);
				pw.println("]");
				pw.close();
			}
		} catch (FileNotFoundException e1) {}
	}
	
	public static HashMap<String, String> readFile(String fileName) throws SyntaxError {
		HashMap<String, String> output = new HashMap<String, String>();
		String line = "";
		String name;
		String ipPort;
		BufferedReader bfr = null;
		while (true) {
			try {
				bfr = new BufferedReader(new FileReader(fileName));
				bfr.readLine(); //skip first line
				while ((line = bfr.readLine()) != null) {
					int start = line.indexOf(QUOTE);
					if (start != -1) {
						start++;
						int end = line.indexOf(QUOTE, start);
						name = line.substring(start, end);
						start = line.indexOf(QUOTE, end + 1) + 1;
						end = line.indexOf(QUOTE, start);
						ipPort = line.substring(start, end);
						output.put(name, ipPort);
					}
				}
				bfr.close();
				return output;
			} catch (FileNotFoundException fnf) {
				createAndPopulateJsonFile(fileName);
			} catch (Exception e) {
				throw new SyntaxError();
			}
		}
	}
	
	public static void writeFile(String fileName, HashMap<String, String> outputData) throws IOException {
		PrintWriter pw = new PrintWriter(fileName);
		pw.println(START_BRACKET);
		int lastElement = outputData.size() - 1;
		int i = 0;
		for (String key : outputData.keySet()) {
			if (i == lastElement) {
				pw.println(String.format(JSON_WRITE_FORMAT, key, outputData.get(key)));
			} else {
				pw.println(String.format(JSON_WRITE_FORMAT + ",", key, outputData.get(key)));
			}
			i++;
		}
		pw.println(END_BRACKET);
		pw.close();
	}
	
	public static HashMap<String, String> readString(String json) {
		HashMap<String, String> result = new HashMap<String, String>();
		int start;
		int end;
		String name;
		String ipPort;
		while (true) {
			start = json.indexOf(QUOTE);
			if (start == -1) break;
			start++;
			end = json.indexOf(QUOTE, start);
			name = json.substring(start, end);
			start = json.indexOf(QUOTE, end + 1) + 1;
			end = json.indexOf(QUOTE, start);
			ipPort = json.substring(start, end);
			json = json.substring(end + 1);
			result.put(name, ipPort);
		}
		return result;
	}
}
